import 'package:flutter/material.dart';
import 'package:spring_fairy/api/mood_type_api.dart';
import 'package:spring_fairy/model/store.dart';
import 'package:spring_fairy/util/notify.dart';
import 'package:spring_fairy/widget/mood_widget.dart';
import '../../model/mood_type.dart';



class MoodTypePage extends StatefulWidget {
  const MoodTypePage({super.key});

  @override
  State<MoodTypePage> createState() => _MoodTypePageState();
}

class _MoodTypePageState extends State<MoodTypePage> {
  late final List<MoodWidget> moodTypes;
  late final MoodTypeAPI moodTypeAPI;

  @override
  void initState() {
    super.initState();
    moodTypes = MoodWidget.list;
    moodTypeAPI = MoodTypeAPI();
  }

  final TextEditingController _controller = TextEditingController();

  void _addMoodType() {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: const Text("添加心情"),
        content: TextField(
          controller: _controller,
          decoration: const InputDecoration(labelText: "心情名称"),
        ),
        actions: [
          TextButton(
            onPressed: () {
              if(_controller.text.isEmpty) {
                return ;
              }
              MoodType moodType = MoodType(name: _controller.text);
              _insertMoodType(moodType);
              Navigator.pop(context);
            },
            child: const Text("添加"),
          ),
        ],
      ),
    );
  }

  void _deleteMoodType(int index) {
    setState(() {
      moodTypes.removeAt(index);
    });
  }

  void _insertMoodType(MoodType moodType) async {
    MoodType? currentMoodType = await moodTypeAPI.createMoodType(moodType);
    if(currentMoodType == null) {
      notify('添加失败!', context);
      return ;
    }

    setState(() {
      Store.addMoodType(moodType);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("心情管理")),
      body: RefreshIndicator(child:
      ListView.builder(
        itemCount: moodTypes.length,
        itemBuilder: (context, index) {
          final mood = moodTypes[index];
          return ListTile(
            title: SizedBox(
              width: 60,
              height: 60,
              child: mood.lottie,
            ),
            trailing: IconButton(
              icon: const Icon(Icons.delete, color: Colors.red),
              onPressed: () => _deleteMoodType(index),
            ),
          );
        },
      ),
          onRefresh: _onRefresh),
      // floatingActionButton: FloatingActionButton(
      //   onPressed: _addMoodType,
      //   child: const Icon(Icons.add),
      // ),
    );
  }

  Future<void> _onRefresh() async {
    List<MoodType>? moodTypes = await moodTypeAPI.getAllMoodTypes();
    if(moodTypes == null) {
      return ;
    }
    setState(() {
      Store.setMoodTypes(moodTypes);
      this.moodTypes.clear();
      // this.moodTypes.addAll(moodTypes);
    });
  }
}
